package com.jkgl.socket;

import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.fastjson2.JSON;
import com.jkgl.common.core.domain.model.LoginUser;
import com.jkgl.common.utils.SecurityUtils;
import com.jkgl.common.utils.spring.SpringUtils;
import com.jkgl.entity.ChatHistory;
import com.jkgl.entity.UserInfoDayEntity;
import com.jkgl.model.socket.MessageVO;
import com.jkgl.service.GPTChatService;
import com.jkgl.service.IChatHistoryService;
import com.jkgl.service.UserInfoDayService;
import com.jkgl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import com.jkgl.framework.web.service.TokenService;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/GptSocket")
public class GPTSocket {

    private Session session;
    private TokenService tokenService;

    private IChatHistoryService chatHistoryService;

    public GPTSocket(){
        this.tokenService = SpringUtils.getBean(TokenService.class);

        this.chatHistoryService = SpringUtils.getBean(IChatHistoryService.class);
    }

//    用户与session关联
    private final static ConcurrentHashMap<Session,Long> curren = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) throws IOException {
        this.session = session;
        LoginUser loginUser = tokenService.getLoginUser(session.getQueryString().substring(session.getQueryString().indexOf("=") + 1));
        if(loginUser == null){
            onClose();
            return;
        }
        curren.put(session,loginUser.getUserId());
    }

    //Authorization
    @OnClose
    public void onClose() {
        log.info("WebSocket连接关闭");
    }

    @OnMessage
    public void onMessage(String message, Session session) throws NoApiKeyException, InputRequiredException, IOException {
        log.info("来自SessionId:{}的消息:{}", session.getId(), message);
        GenerationResult generationResult = GPTChatService.callWithMessage(message);
        String answer = generationResult.getOutput().getChoices().get(0).getMessage().getContent();
        ChatHistory chatHistory = new ChatHistory();
        chatHistory.setAnswer(answer);
        chatHistory.setUserId(curren.get(session));
        chatHistory.setQuestion(message);
        chatHistory.setCreateTime(LocalDateTime.now());
        chatHistoryService.save(chatHistory);
        session.getBasicRemote().sendText(answer);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("Session:{}的WebSocket发生错误", session.getId(), error);
    }

    public Session getSession() {
        return session;
    }

    public String getSessionId() {
        return session.getId();
    }


//    public static void main(String[] args) {
//        curren.forEach((key,value) ->{
//            try {
//                System.out.println(value);
//                value.getBasicRemote().sendText("1111");
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        });
//    }

}